package com.zlz.security.securitydemo1.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlz.security.securitydemo1.entity.Users;
import com.zlz.security.securitydemo1.mapper.UserMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author: zlz
 * @date: 2021/3/21 21:08
 * @description:
 * @since: JDK1.8
 */
@Service("userDetailService")
public class UserService extends ServiceImpl<UserMapper, Users> implements UserDetailsService {
    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        Users users = userMapper.selectOne(new QueryWrapper<Users>().eq("name", name));
        if (Objects.isNull(users)) {
            throw new UsernameNotFoundException("用户不存在");
        }
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("manager,ROLE_zlz");
        return new User(users.getName(), new BCryptPasswordEncoder().encode(users.getPwd()), auths);
    }
}
